package week4.day22;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author fengzihao
 * @Date 2024-05-06 19:54
 */
public class SortedStoring {
    public static void main(String[] args) {
        String[] words = {"verb:eat","verb:drink","verb:sleep","verb:play","noun:rice","noun:meat","noun:hand","noun:hair"};
        File fileVerb = new File("verb.txt");
        File fileNoun = new File("noun.txt");
        for (String word : words) {
            String[] partOfSpeechAndWords = word.split(":");
            FileOutputStream fileOutputStream = null;
            if (("verb".equals(partOfSpeechAndWords[0]))) {
                try {
                    fileOutputStream = new FileOutputStream(fileVerb,true);
                } catch (FileNotFoundException e) {
                    try {
                        fileVerb.createNewFile();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
                try {
                    fileOutputStream.write(word.getBytes());
                    fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                continue;
            }
            try {
                fileOutputStream = new FileOutputStream(fileNoun ,true);
            } catch (FileNotFoundException e) {
                try {
                    fileVerb.createNewFile();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            try {
                fileOutputStream.write(word.getBytes());
                fileOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
